
#include "CobwebMql.h"
#include "Debug.h"
#include <sstream>
using namespace std;

CobWebMQL:: CobWebMQL(const char *host, const char *dbname, const char *user, const char * pwd, int max)
{
	m_dbHost = host;
	m_pDB = NULL;
	m_dbUser = user;
	m_dbPass = pwd;
        m_dbName = dbname;
	MAXT = max;
}

CobWebMQL:: ~CobWebMQL()
{
	if(m_pDB != NULL)
		mysql_close(m_pDB);
	m_pDB = NULL;
}

bool CobWebMQL :: Initialize()
{
	if(m_pDB == NULL)
	{
		try {
			m_pDB = mysql_init(NULL);
			mysql_options(m_pDB, MYSQL_SET_CHARSET_NAME, "utf8");
			if(NULL == mysql_real_connect( m_pDB,
						m_dbHost.c_str(),
						m_dbUser.c_str(),
						m_dbPass.c_str(),
						m_dbName.c_str(),
						3306,
						NULL,     /* my_bool compress */
						1))
			{
				ERRO << mysql_error(m_pDB) << endl;
				mysql_close(m_pDB);
				m_pDB = NULL;
				cerr<<"Could not connect "<< m_dbName <<", "<< m_dbHost << ", " << m_dbUser << endl;
                                return false;
			}
			for(int i=0; i< MAXT; i++)
			{
				ostringstream  sql;
				sql << "create table sns"<< i << "(nid INT, name varchar(60),friends text, expire INT, primary key(nid))TYPE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ci;";
				if( mysql_real_query(m_pDB, sql.str().c_str(), sql.str().length()) != 0 )
					ERRO <<mysql_errno(m_pDB)<<":"<< mysql_error(m_pDB) << endl;
			}
                       return true;
		}
		catch (...) {
			cerr << "cobweb Initialize ERROR " <<  "\n";
			return false;
		}
	}
	return true;
}

int CobWebMQL :: Save(char *key, char *name, char *val, long expire )
{
	ostringstream sql;
        int nid = atoi(key);
	sql <<"INSERT INTO sns"<<(nid%MAXT) <<" VALUES("<< nid <<", '"<<name<<"','"<<val<<"',"<< expire<< ")";
	try{
                mysql_ping(m_pDB);
		if( mysql_real_query(m_pDB, sql.str().c_str(), sql.str().length()) == 0 )
			return 0;
		else
			ERRO << mysql_errno( m_pDB)<<":"<< mysql_error( m_pDB) << endl;
		return 1;
	}catch(...)
	{
		return -1;
	}
}

int CobWebMQL :: Replace(char *key, char *name ,char *val, long expire )
{
	ostringstream sql;
        int nid = atoi(key);
	sql <<"UPDATE sns"<<(nid%MAXT)<<" SET name='"<<name<<", friends='"<< val<<"', expire="<<expire <<" WHERE nid="<<nid;
	try{
		mysql_ping(m_pDB);
		if( mysql_real_query(m_pDB, sql.str().c_str(), sql.str().length()) == 0 )
			return 0;
		else
			ERRO << mysql_errno( m_pDB)<<":"<< mysql_error( m_pDB) << endl;
		return 1;
	}catch(...)
	{
		return -1;
	}
}

int CobWebMQL :: Fetch(char *key,  string &name, string &val, long &expire )
{
	try{		// Acquire a cursor for the table.
		int nid = atoi(key);
		ostringstream sql;
		sql << "SELECT name, friends, expire FROM sns"<<(nid%MAXT) <<" WHERE nid="<<nid;
 mysql_ping(m_pDB);
		if(mysql_real_query(m_pDB, sql.str().c_str(), sql.str().length() ) != 0){
			cerr << mysql_error( m_pDB) << endl;
			return 1;
		}
		MYSQL_RES *result;
		MYSQL_ROW row;

		result = mysql_store_result( m_pDB);
		if(result == NULL){
			cerr << mysql_error(m_pDB) << endl;
			return 1;
		}
		long rownum = mysql_num_rows(result);
		if (rownum <= 0 )
		{
			mysql_free_result(result);
			return 1;
		}
		if ((row = mysql_fetch_row(result)))
		{
                     name =(char *)row[0];
                     val  = (char *)row[1];
                     expire = atol(row[2]);
                }
		mysql_free_result(result);
                return 0; 
	}
	catch (...) {
                return -1;
	}
}
